package zktimes

import (
	"database/sql"
	"time"

	_ "github.com/alexbrainman/odbc"
	"github.com/axgle/mahonia"
)

//定义参数
const (
	ZKTimesConnStr = "DSN=zktimes;UID=km;PWD=kmtech"
)

//ZKUser 中控考勤机用户
type ZKUser struct {
	UserID   int
	UserName string
	Dept     int
	Checks   map[string][]string
}

//GetUsers for getting all user of USERINFO
func GetUsers() []*ZKUser {
	var users []*ZKUser

	conn, err := sql.Open("odbc", ZKTimesConnStr)
	if err != nil {
		panic(err)
	}
	defer conn.Close()

	//Get all user
	stmt, err := conn.Prepare(`select USERID,NAME,DEFAULTDEPTID from USERINFO where DEFAULTDEPTID > 1 order by DEFAULTDEPTID`)
	if err != nil {
		panic(err)
	}
	defer stmt.Close()
	row, _ := stmt.Query()
	defer row.Close()
	if mahonia.GetCharset("gbk") == nil {
		panic("charset not supported")
	}
	dec := mahonia.NewDecoder("gbk")
	for row.Next() {
		var u ZKUser
		row.Scan(&u.UserID, &u.UserName, &u.Dept)
		u.UserName = dec.ConvertString(u.UserName)
		u.getCheckInOut()
		users = append(users, &u)
	}
	return users
}

//getCheckInOut 获取考勤信息并赋值到ZKUser中
func (zku *ZKUser) getCheckInOut() {
	conn, err := sql.Open("odbc", ZKTimesConnStr)
	if err != nil {
		panic(err)
	}
	defer conn.Close()
	stmt, err := conn.Prepare("select CHECKTIME from CHECKINOUT where USERID = ?")
	if err != nil {
		panic(err)
	}
	defer stmt.Close()
	row, _ := stmt.Query(zku.UserID)
	defer row.Close()

	//获取所有考勤记录并归入当天
	checkData := make(map[string][]string)
	for row.Next() {
		var checktime time.Time
		row.Scan(&checktime)
		dateStr := time.Date(checktime.Year(), checktime.Month(), checktime.Day(), 0, 0, 0, 0, time.Local).Format("01-02-06")
		checkData[dateStr] = append(checkData[dateStr], checktime.Format("01-02-06 15:04:05"))
	}

	zku.Checks = checkData
}
